#include <iostream>

#include <cstdlib>
#include <ctime>

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

void handler(int signo)
{
    int state = 0;
    pid_t rid = 0;
    std::cout << "my pid: " << getpid() << " catch signal: " << signo << std::endl;
    while ((rid = waitpid(-1, &state, WNOHANG)) > 0)
    {
        std::cout << "wait child: " << rid << std::endl;
        std::cout << "exit code: " << WEXITSTATUS(state) << std::endl;
        if (!WIFEXITED(state))
            std::cout << "sign code: " << (state & 0x7F) << std::endl;
        if ((state >> 7) & 0x01)
            std::cout << "core dump" << std::endl;
        std::cout << std::endl;
    }
}

int main()
{
    signal(17, handler);
    // signal(17, SIG_IGN);

    srand((unsigned int)time(nullptr));

    for (int i = 0; i < 10; ++i)
    {
        pid_t id = fork();
        if (id == 0)
        {
            std::cout << "I am child process: " << getpid() << " ppid: " << getppid() << std::endl;
            sleep(10);
            std::cout << "child exit" << std::endl;
            exit(0);
        }
        else if (id < 0)
            exit(1);
        sleep(rand() % 5 + 3);
    }

    while (true)
    {
        std::cout << "I am parent process: " << getpid() << std::endl;
        sleep(1);
    }

    return 0;
}